package com.equdao.car_violation_inquiry.service.impl;

import com.alibaba.fastjson.JSON;
import com.equdao.car_violation_inquiry.dao.BasicCarDaoMapper;
import com.equdao.car_violation_inquiry.dao.WebPageViolationDetailDaoMapper;
import com.equdao.car_violation_inquiry.dao.WebPageViolationInfoDaoMapper;
import com.equdao.car_violation_inquiry.enums.OriginTypeEnum;
import com.equdao.car_violation_inquiry.enums.ResultEnum;
import com.equdao.car_violation_inquiry.pojo.*;
import com.equdao.car_violation_inquiry.service.WebPageService;
import com.equdao.car_violation_inquiry.utils.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author: 杨忠强
 * @Date: 2018/6/28 14:55
 * @Description:
 */

@Service
public class WebPageServiceImpl implements WebPageService{


    @Resource
    private HttpAPIServiceWanWu httpAPIServiceWanWu;

    @Resource
    private HttpAPIService httpAPIService;

    @Autowired
    private WebPageViolationInfoDaoMapper  webPageViolationInfoDaoMapper;

    @Autowired
    private WebPageViolationDetailDaoMapper  webPageViolationDetailDaoMapper;

    @Autowired
    private BasicCarDaoMapper basicCarDaoMapper;


    //万物
    @Value("${wz.token}")
    private String userToken;
    @Value("${wz.user}")
    private String user;
    @Value("${wz.api}")
    private String wwapi;
    @Value("${wz.url}")
    private String wwurl;

    //广州桓达
    @Value("${wm.username}")
    private String username;
    @Value("${wm.url}")
    private String wmurl;


    @Async
    @Override
    public Integer findHDViolationInfo(List<BasicCarDO> list) {



        for (BasicCarDO basicCarDO : list) {

            Map<String, Object> map = new HashMap<>();
            map.put("username", username);
            String password = MD5Utils.Md5(username).toUpperCase();
            map.put("password", password);
            map.put("carNum", basicCarDO.getVehicleNo());
            map.put("engineNumber", basicCarDO.getEngineNo());
            map.put("vin", basicCarDO.getFrameNo());
            map.put("carType", "02");
            map.put("area", basicCarDO.getVehicleNo().substring(0, 1));
            map.put("time", String.valueOf(System.currentTimeMillis() / 1000L));

            String signStr = username + password + basicCarDO.getVehicleNo() + basicCarDO.getEngineNo() +
                    basicCarDO.getFrameNo() + "02" + basicCarDO.getVehicleNo().substring(0, 1) +
                    String.valueOf(System.currentTimeMillis()  / 1000L);

            System.out.println("传入id"+basicCarDO.getId());
            String sign = String.valueOf(MD5Utils.Md5(signStr));
            map.put("sign", sign);
            HttpResult httpResult = null;
            try {
                // TODO 如果失败了要处理   保存
                httpResult = httpAPIService.doPost(wmurl, map);
                String resultBody = httpResult.getBody();
                System.out.println("输出的body" + resultBody);
                LocalWMResponseVO localWmResponseVO = JSON.parseObject(resultBody, LocalWMResponseVO.class);
                WebPageViolationInfoDO webPageViolationInfoDO = new WebPageViolationInfoDO();
                webPageViolationInfoDO.setVehicleNo(basicCarDO.getVehicleNo());
                webPageViolationInfoDO.setFrameNo(basicCarDO.getFrameNo());
                webPageViolationInfoDO.setEngineNo(basicCarDO.getEngineNo());
                webPageViolationInfoDO.setData(resultBody);
                webPageViolationInfoDO.setStatus(ResultEnum.SUCCESS.getCode());
                webPageViolationInfoDO.setOrigin(OriginTypeEnum.HDDATA.getName());
                webPageViolationInfoDaoMapper.saveWebPageViolationInfo(webPageViolationInfoDO);

                //如果返回正常数据
                // TODO  处理返回异常的诗句

                //创建存入数据库的实体类
                ArrayList<WebPageViolationDetailDO> detailDOArrayList = new ArrayList<>();
                if ("success".equals(localWmResponseVO.getState())) {
                    if (!localWmResponseVO.getResult().getHistorys().isEmpty()) {
                    //如果有明细
                        for (LocalWMResponseVO.ResultEntity.HistorysEntity historysBean : localWmResponseVO.getResult().getHistorys()) {
                            WebPageViolationDetailDO webPageViolationDetailDO = new WebPageViolationDetailDO();
                            webPageViolationDetailDO.setCph(basicCarDO.getVehicleNo());
                            webPageViolationDetailDO.setCjh(basicCarDO.getFrameNo());
                            webPageViolationDetailDO.setFdj(basicCarDO.getEngineNo());
                            webPageViolationDetailDO.setMsg(localWmResponseVO.getState());//返回状态
                            webPageViolationDetailDO.setWzsj(historysBean.getOccur_date());
                            webPageViolationDetailDO.setWzdd(historysBean.getOccur_area());
                            webPageViolationDetailDO.setWzxw(historysBean.getInfo());
                            webPageViolationDetailDO.setWzfk(historysBean.getMoney());
                            webPageViolationDetailDO.setWzjf(historysBean.getFen());
                            webPageViolationDetailDO.setCsmc(historysBean.getCity());
                            webPageViolationDetailDO.setCsdm("");
                            webPageViolationDetailDO.setWfdm(historysBean.getIllegal_code());
                            webPageViolationDetailDO.setClbj(historysBean.getFine_status());
                            webPageViolationDetailDO.setOrigin(OriginTypeEnum.HDDATA.getName());

                            webPageViolationDetailDO.setFlag(basicCarDO.getFlag());
                            detailDOArrayList.add(webPageViolationDetailDO);
                        }
                            webPageViolationDetailDaoMapper.saveWebPageViolationDetails(detailDOArrayList);



                    } else {
                        //如果没有明细
                        WebPageViolationDetailDO webPageViolationDetailDO = new WebPageViolationDetailDO();
                        webPageViolationDetailDO.setCph(basicCarDO.getVehicleNo());
                        webPageViolationDetailDO.setCjh(basicCarDO.getFrameNo());
                        webPageViolationDetailDO.setFdj(basicCarDO.getEngineNo());
                        webPageViolationDetailDO.setMsg(localWmResponseVO.getState());
                        webPageViolationDetailDO.setOrigin(OriginTypeEnum.HDDATA.getName());
                        webPageViolationDetailDO.setFlag(basicCarDO.getFlag());
                        detailDOArrayList.add(webPageViolationDetailDO);

                        webPageViolationDetailDaoMapper.saveWebPageViolationDetails(detailDOArrayList);
                    }
                    //查询成功,修改原数据状态为1   已查询
                    Integer isSuccess = basicCarDaoMapper.updateBasicCarById(basicCarDO.getId());

                }else if ("fail".equals(localWmResponseVO.getState())){
                    if ("加载超时，请稍后再试".equals(localWmResponseVO.getError_message()) || "系统出现异常!".equals(localWmResponseVO.getError_message())){
                        System.out.println("网络故障"+"传入id" +basicCarDO.getId());
                    }else {
                        WebPageViolationDetailDO webPageViolationDetailDO = new WebPageViolationDetailDO();
                        webPageViolationDetailDO.setCph(basicCarDO.getVehicleNo());
                        webPageViolationDetailDO.setCjh(basicCarDO.getFrameNo());
                        webPageViolationDetailDO.setFdj(basicCarDO.getEngineNo());
                        webPageViolationDetailDO.setMsg(localWmResponseVO.getError_message());
                        webPageViolationDetailDO.setOrigin(OriginTypeEnum.HDDATA.getName());
                        webPageViolationDetailDO.setFlag(basicCarDO.getFlag());
                        webPageViolationDetailDaoMapper.saveWebPageViolationDetails(detailDOArrayList);
                        Integer isSuccess = basicCarDaoMapper.updateBasicCarById(basicCarDO.getId());
                        System.out.println("传入信息错误"+"传入id"+basicCarDO.getId());
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        return null;
    }

    @Async
    @Override
    public Integer findWWViolationInfo(List<BasicCarDO> list) {

        /*根据用户请求参数查询上游*/
        for (BasicCarDO basicCarDO : list) {
            Map<String, Object> map = new HashMap<>();
            map.put("user", user);
            map.put("token", userToken);
            map.put("api", wwurl);
            map.put("cph", basicCarDO.getVehicleNo());
            map.put("cx", "02");
            map.put("cjh", basicCarDO.getFrameNo());
            map.put("fdj", basicCarDO.getEngineNo());

            String provinceCode = CityCodeUtils.getProvinceCode(basicCarDO.getVehicleNo().substring(0, 1));
            if (!"".equals(provinceCode)) {
                map.put("assign", provinceCode); //浙江
                System.out.println(provinceCode);
            }
            HttpResult httpResult = null;
            System.out.println("传入的id----->:" + basicCarDO.getId());

            try {
                httpResult = httpAPIServiceWanWu.doPost(wwurl, map);
                String resultBody = httpResult.getBody();
                System.out.println("输出的body---" + resultBody);
                ResponseUpstreamBean responseUpstreamBean = JSON.parseObject(resultBody, ResponseUpstreamBean.class);
                WebPageViolationInfoDO webPageViolationInfoDO = new WebPageViolationInfoDO();
                webPageViolationInfoDO.setVehicleNo(basicCarDO.getVehicleNo());
                webPageViolationInfoDO.setFrameNo(basicCarDO.getFrameNo());
                webPageViolationInfoDO.setEngineNo(basicCarDO.getEngineNo());
                webPageViolationInfoDO.setData(resultBody);
                webPageViolationInfoDO.setStatus(ResultEnum.SUCCESS.getCode());
                webPageViolationInfoDO.setOrigin(OriginTypeEnum.WWDATA.getName());
                webPageViolationInfoDaoMapper.saveWebPageViolationInfo(webPageViolationInfoDO);

                //解析返回来的数据 bizModel = JSON.parseObject(data,YibaoResultBizModel.class);

                if (responseUpstreamBean.getCode() != 502 && responseUpstreamBean.getCode() != 503) {
                    ArrayList<WebPageViolationDetailDO> detailDOArrayList = new ArrayList<>();
                if (!responseUpstreamBean.getData().isEmpty()) {


                    //将查询到的数据存入明细表里

                    for (ViolationDetails details : responseUpstreamBean.getData()) {
                        WebPageViolationDetailDO webPageViolationDetailDO = new WebPageViolationDetailDO();
                        webPageViolationDetailDO.setCph(basicCarDO.getVehicleNo());
                        webPageViolationDetailDO.setCjh(basicCarDO.getFrameNo());
                        webPageViolationDetailDO.setFdj(basicCarDO.getEngineNo());
                        webPageViolationDetailDO.setMsg(responseUpstreamBean.getMsg());
                        webPageViolationDetailDO.setWzsj(details.getWzsj());
                        webPageViolationDetailDO.setWzdd(details.getWzdd());
                        webPageViolationDetailDO.setWzxw(details.getWzxw());
                        webPageViolationDetailDO.setWzfk(details.getWzfk());
                        webPageViolationDetailDO.setWzjf(details.getWzjf());
                        webPageViolationDetailDO.setCsmc(details.getCsmc());
                        webPageViolationDetailDO.setCsdm(details.getCsdm());
                        webPageViolationDetailDO.setWfdm(details.getWfdm());
                        webPageViolationDetailDO.setClbj(details.getClbj());
                        detailDOArrayList.add(webPageViolationDetailDO);
                    }

                    System.out.println("传入的list====>" + detailDOArrayList);
                    Integer secce = webPageViolationDetailDaoMapper.saveWebPageViolationDetails(detailDOArrayList);

                } else {
                    WebPageViolationDetailDO webPageViolationDetailDO = new WebPageViolationDetailDO();
                    webPageViolationDetailDO.setCph(basicCarDO.getVehicleNo());
                    webPageViolationDetailDO.setCjh(basicCarDO.getFrameNo());
                    webPageViolationDetailDO.setFdj(basicCarDO.getEngineNo());
                    webPageViolationDetailDO.setMsg(responseUpstreamBean.getMsg());

                    detailDOArrayList.add(webPageViolationDetailDO);
                    webPageViolationDetailDaoMapper.saveWebPageViolationDetails(detailDOArrayList);
                }
                //加入成功   修改原数据状态为1(网络故障除外)   已查询
                    // TODO  未完善
                    Integer isSuccess = basicCarDaoMapper.updateBasicCarById(basicCarDO.getId());
                }

            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return 1; //成功

    }
}
